package com.seecode.Database;

/**
 * Created by Administrator on 2017/10/18.
 */



import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.seecode.Logs;
import com.seecode.Utils.Utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;


public class Fuxi {

    public static MyDataBaseHelper dbHelper;

    private String sqlBeforeExec=null;
    private String sqlExec = null;
    static String tableName="";
    public int count=0;
    public String[] nameList;
    public Object[] valueList;
    public boolean  isFirstSave=true;

    public static void DataBaseInit(Context mContext){
         if(dbHelper == null) {
             dbHelper = new MyDataBaseHelper(mContext, "code.db", null, 1);

             Logs.i("database Init");
         }

    }

    public  Fuxi(){

        keyInit();
        createTable();
    }

    public void createTable(){


        if( !Utils.getPreBoolValues(tableName)){

            String createSql = "create table if not exists  "+tableName+" ( id integer primary key autoincrement,";
            int i=0;
            Logs.i("it have size of member"+count);
            for( i=0; i< count-1;i++){

                createSql +=nameList[i]+" string ,";
            }
            createSql +=nameList[i]+" string );";
            Logs.i("createTable not have it will be create :"+createSql);
            dbHelper.exeSql(createSql);
            Utils.setPreBoolValues(tableName,true);
        }else{
            Logs.i("table already exists");
        }
    }
    public void  keyInit(){



        Class c = getClass();
        String name = c.getName();
        this.tableName = name.substring(name.lastIndexOf(".")+1,name.length()).toLowerCase();

        Field[] fs =  c.getDeclaredFields();
        if(count == 0){
            count = fs.length;
        }


        if(nameList == null){

            nameList = new String[count];

        }
        Logs.i("this is first to save");
        int other=0;
        for(int i=0,j=0; i< count ; i++,j++){

            Field f = fs[i];
            f.setAccessible(true);
            //if os version big then 5.0 it will add 2 rubush ziduan
            if(isHightSystemMember(f.getName())){
                j--;other++;
                Logs.i("what hell youdo 5.0 android");
                continue;
            }
            nameList[j] = f.getName().toLowerCase();
        }
        count=count-other;
        this.sqlBeforeExec="insert into " + tableName + "(";
        for(int i=0 ; i < count  ;i++){

            if( i == count -1){

                this.sqlBeforeExec+=nameList[i]+") values('";
                break;

            }
            this.sqlBeforeExec+=nameList[i]+",";
        }

        Logs.i("sql "+this.sqlBeforeExec);

    }

    public static boolean isHightSystemMember(String name){

        //if system big then 5.0 it will add 2 memeber invisible
        //what is seem autocreate for serialize ok I was give up---_----
        if( name.equals("$change")  || name.equals("serialVersionUID")){

            return true;
        }
        return false;
    }
    public void getValue(){


        Class c = getClass();
        Field[] fs =  c.getDeclaredFields();

        int n=count;

        valueList = new String[count];
        for(int i=0; i< n; i++){


            Field f = fs[i];
            f.setAccessible(true);
            try{
                Logs.i("name: "+f.getName()+"  value: "+f.get(this));

                valueList[i] = f.get(this);

                //Logs.i("name: "+nameList[i]+" value: "+valueList[i]);
            }catch(Exception e){

                e.printStackTrace();
            }

        }



    }//end getvalue();

    public  void save(){

        getValue();
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();

        for(int i=0; i< count;i++){

            values.put(nameList[i],valueList[i].toString());
        }
        db.insert(tableName,null,values);


    }

    public static <T> List<T> findAll(Class<T> modelClass ) {
        List<T> dataList = new ArrayList<T>();
        try{

            //already be a  class tyep so not use getClass
            String name = modelClass.getName();


            String tName= name.substring(name.lastIndexOf(".")+1,name.length()).toLowerCase();
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            Cursor cursor = db.query(tName,null,null,null,null,null,null);

            Field[] fs = modelClass.getDeclaredFields();
            int n = fs.length;

              if(cursor.moveToFirst())
              {



                    //Logs.i(rs.getString("name"));

                    do {
                        T modelInstance = (T) modelClass.newInstance();
                        for (int i = 0; i < n; i++) {
                            fs[i].setAccessible(true);
                            if(isHightSystemMember(fs[i].getName())){
                                Logs.i("fuck find other member you not want to see"+fs[i].getName());
                                continue;
                            }
                            String memberName =fs[i].getName().toLowerCase();
                            //it should cation if is not up or low suggest to handle low
                            Logs.i("colum "+memberName);

                            fs[i].set(modelInstance, cursor.getString(cursor.getColumnIndex(memberName)));


                        }
                        Logs.i("data once");
                        dataList.add(modelInstance);
                    }while(cursor.moveToNext());


              }




            return dataList;

        }catch(Exception e){

           e.printStackTrace();
        }

        return dataList;
    }


}
